package com.czy.service.impl;

import com.czy.mapper.StudentMapper;
import com.czy.pojo.PageResult;
import com.czy.pojo.Student;
import com.czy.pojo.StudentPage;
import com.czy.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> page(StudentPage page) {
        //设置分页参数
        PageHelper.startPage(page.getPage(), page.getPageSize());

        //执行SQL语句
        List<Student> studentList = studentMapper.list(page);

        //封装结果
        Page<Student> pageList = (Page<Student>) studentList;

        return new PageResult<Student>(pageList.getTotal(), pageList.getResult());
    }

    @Override
    public void insert(Student student) {
        //补全基础属性 创建时间和修改时间
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        //调用mapper新增学员信息
        studentMapper.insert(student);
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    @Override
    public void update(Student student) {
        //补全基础属性
        student.setUpdateTime(LocalDateTime.now());

        //调用studentMapper执行修改语句
        studentMapper.update(student);
    }

    @Override
    public void delete(ArrayList<Integer> ids) {
        studentMapper.delete(ids);
    }

    @Override
    public void updateViolation(Integer id, Integer score) {
        //先查询出上次的违纪次数和扣除分数
        Student student = studentMapper.selectViolation(id);

        //对查出数据进行处理后
        student.setId(id);
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));

        //执行SQL语句修改违纪次数和分数
        studentMapper.updateViolation(student);
    }
}
